package cn.hzc.fortess.core.interceptor;

import cn.hzc.fortess.core.common.RenderUtil;
import cn.hzc.fortess.core.common.constant.JwtConstants;
import cn.hzc.fortess.core.util.JwtTokenUtil;
import cn.hzc.fortess.spi.bean.JwtResponse;
import cn.hzc.fortess.spi.bean.JwtExceptionEnum;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtAuthApiInteceptor extends HandlerInterceptorAdapter {

    private static final Logger log= LoggerFactory.getLogger(JwtAuthApiInteceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof org.springframework.web.servlet.resource.ResourceHttpRequestHandler) {
            return true;
        }
        return check(request, response);
    }

    private boolean check(HttpServletRequest request, HttpServletResponse response) {
        if (request.getServletPath().equals(JwtConstants.AUTH_PATH)) {
            return true;
        }
        final String requestHeader = request.getHeader(JwtConstants.AUTH_HEADER);
        log.debug("jwt request header:{}",requestHeader==null?"[null]":requestHeader);
        /*
         * JWT的用法

         *客户端接收服务器返回的JWT，将其存储在Cookie或localStorage中。

         *此后，客户端将在与服务器交互中都会带JWT。如果将它存储在Cookie中，就可以自动发送，但是不会跨域，因此一般是将它放入HTTP请求的Header Authorization字段中。

         *Authorization: Bearer
         *
         * */
        if (requestHeader != null && requestHeader.startsWith(JwtConstants.BEARER)) {
            final String authToken = requestHeader.substring(JwtConstants.BEARER.length());
            try {
                if (JwtTokenUtil.isTokenExpired(authToken)) {
                    RenderUtil.renderJson(response,new JwtResponse(JwtExceptionEnum.TOKEN_EXPIRED));
                    return false;
                }
            } catch (JwtException e) {
                RenderUtil.renderJson(response, new JwtResponse(JwtExceptionEnum.TOKEN_EXCEPTION));
                return false;
            }
        } else {
            RenderUtil.renderJson(response, new JwtResponse(JwtExceptionEnum.TOKEN_EXCEPTION));
            return false;
        }
        return true;
    }

}
